<script setup lang='ts'>
import type { OptionsType, PlusColumn } from 'plus-pro-components'
import type { VxeGridProps } from 'vxe-table'

import PublishError from '@/purchase-pages/pricing-tool/add-or-edit-pricing/components/publish-error.vue'
import { useDeleteProduct, useGetProductCategoryOptions, useGetProductPage, usePublishProduct } from '@fl/api/purchase'
import { SearchForm, SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { treeFindLabel } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'

import AddPricing from './components/add-pricing.vue'
import { PRICING_PRODUCT_STATUS, PRICING_PRODUCT_STATUS_MAP } from './constant'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: '/purchase-pages/pricing-tool/goods-management',
})

const { createConfirmModal } = useMessage()
const router = useRouter()

const showAddPricing = ref<boolean>(false)
const showPublishError = ref<boolean>(false)
const errorData = ref<any>({})

const initialState = {
    goodsCategory: '',
    productName: '',
}
const state = ref(cloneDeep(initialState))

const searchConditions = ref(cloneDeep(initialState))
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const getProductPageParams = computed(() => ({
    ...searchConditions.value,
    page: tablePage.currentPage,
    size: tablePage.pageSize,
}))

const {
    data: productPageData,
    isLoading: isGetProductPageLoading,
    total: productTotal,
} = useGetProductPage(getProductPageParams)
const { data: productCategoryOptionsData, isLoading: isGetProductCategoryOptionsLoading } = useGetProductCategoryOptions()
const { isPending: _isDeleteProductPending, mutate: deleteProduct } = useDeleteProduct()
const { isPending: _isPublishProductPending, mutate: publishProduct } = usePublishProduct()

// #region Form
const isFormLoading = computed(() => isGetProductCategoryOptionsLoading.value)

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        label: '组合商品名称',
        prop: 'productName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '组合商品类目',
        options: productCategoryOptionsData as OptionsType,
        prop: 'categoryId',
        valueType: 'select',
    },
]

function submit() {
    searchConditions.value = cloneDeep(state.value)
    resetTablePage()
}

function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    resetTablePage()
}

function resetTablePage() {
    tablePage.currentPage = 1
    tablePage.pageSize = 10
}
// #endregion

// #region Table
const isTableLoading = computed(() => isGetProductPageLoading.value)
const tableData = ref<any[]>([])

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 60 },
        { field: 'productName', title: '组合商品名称' },
        { field: 'enterpriseName', title: '招标单位' },
        { field: 'categoryName', title: '组合商品类目' },
        { field: 'createBy', title: '创建人', width: 100 },
        { field: 'createTime', title: '创建日期', width: 170 },
        // { field: 'endTime', title: '投标截止时间', width: 170 },
        { field: 'status', slots: { default: 'status' }, title: '状态', width: 100 },
        { slots: { default: 'operation' }, title: '操作', width: 200 },
    ],
})

watchEffect(() => {
    tableData.value = cloneDeep(productPageData.value)
    tablePage.total = productTotal.value
})
// #endregion

// #region UI Listener
function onEditBtnClick(row: any) {
    router.push({ path: '/purchase-pages/pricing-tool/add-or-edit-pricing', query: { id: row.id } })
}

function onCheckDetailBtnClick(row: any) {
    router.push({ path: '/purchase-pages/pricing-tool/add-or-edit-pricing', query: { id: row.id } })
}

// function onChooseSupplierBtnClick(row: any) {
//     router.push({ path: '/purchase-pages/pricing-tool/add-or-edit-pricing', query: { activeName: 'chooseSupplier', id: row.id } })
// }

function onPublishBtnClick(row: any) {
    createConfirmModal({
        content: '确定要发布该组价商品吗？',
        onSuccess: () => {
            publishProduct(row.id, {
                onSuccess(data: any) {
                    if (data.code === 200) {
                        ElMessage.success('操作成功')
                        router.back()
                    }
                    else if (data.code === 500) {
                        showPublishError.value = true
                        errorData.value = data.data || { msg: data.msg }
                    }
                    else {
                        ElMessage.error('操作失败')
                    }
                },
            })
        },
        title: '提示',
    })
}

function onDeleteBtnClick(row: any) {
    createConfirmModal({
        content: '确定要删除该组价商品吗？',
        onSuccess: () => {
            deleteProduct(row.id, {
                onSuccess() {
                    ElMessage.success('操作成功')
                },
            })
        },
        title: '提示',
    })
}

function onAddBtnClick() {
    showAddPricing.value = true
}
// #endregion
</script>

<template>
    <el-card mb-20
             shadow="never"
    >
        <el-skeleton v-if="isFormLoading"
                     animated
        />

        <SearchForm v-else
                    v-model="state"
                    :columns="columns"
                    submit-text="查询"
                    :row-props="{ gutter: 40 }"
                    @submit="submit"
                    @reset="reset"
        />
    </el-card>

    <el-card shadow="never">
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isTableLoading"
                     :data="tableData"
        >
            <template #operation="{ row }">
                <el-button v-if="row.status === PRICING_PRODUCT_STATUS_MAP.NOT_PUBLISHED"
                           text
                           type="primary"
                           class="!p-4"
                           @click="onEditBtnClick(row)"
                >
                    录入
                </el-button>

                <el-button v-else
                           text
                           type="primary"
                           class="!p-4"
                           @click="onCheckDetailBtnClick(row)"
                >
                    查看
                </el-button>
                <!--
                <el-button v-if="row.status === PRICING_PRODUCT_STATUS_MAP.PUBLISHED"
                           text
                           class="!p-4 !text-[#86909C]"
                           @click="onChooseSupplierBtnClick(row)"
                >
                    供应商选取
                </el-button> -->

                <el-button v-if="row.status === PRICING_PRODUCT_STATUS_MAP.NOT_PUBLISHED"
                           text
                           class="!p-4 !text-[#86909C]"
                           @click="onPublishBtnClick(row)"
                >
                    发布
                </el-button>

                <el-button text
                           class="!p-4 !text-[#86909C]"
                           @click="onDeleteBtnClick(row)"
                >
                    删除
                </el-button>
            </template>

            <template #toolbar_buttons>
                <el-space class="mb-12">
                    <el-button type="primary"
                               @click="onAddBtnClick"
                    >
                        <div class="i-ic:baseline-add size-16" />
                        新建
                    </el-button>
                </el-space>
            </template>

            <template #status="{ row }">
                <span class="px-8 inline-block border-1 rounded-[3px] border-solid text-[12px]"
                      :class="row.status === PRICING_PRODUCT_STATUS_MAP.PUBLISHED ? ['bg-[#E3F9E9]', 'border-[#2BA471]', 'text-[#2BA471]'] : ['bg-[#FFF1E9]', 'border-[#E37318]', 'text-[#E37318]']"
                >
                    {{ treeFindLabel({ targetValue: row.status, treeData: PRICING_PRODUCT_STATUS }) }}
                </span>
            </template>
        </SearchTable>
    </el-card>

    <AddPricing v-model:visible="showAddPricing" />

    <PublishError v-model:visible="showPublishError"
                  :error-data="errorData"
    />
</template>
